package com.luoqiz.project.mulThreadCopy;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class MulCopyFile {

	private int threadNum = 3; // 线程数量
	private int byteSize = 1024;// 每次写入字节数组长度
	private long threadCopyLen = 0;// 每一个线程需要操作的字节数组长度

	public MulCopyFile() {
	}

	public MulCopyFile(int byteSize, int threadNum) {
		this.byteSize = byteSize;
		this.threadNum = threadNum;
	}

	public void copy(String srcPath, String destPath) {
		try {
			File srcFile = new File(srcPath);
			long srcFileLen = srcFile.length();
			RandomAccessFile srdaf = new RandomAccessFile(srcFile, "r");
			RandomAccessFile drdaf = new RandomAccessFile(new File(destPath), "rw");
			long a = srcFileLen % threadNum;
			if (a != 0) {
				threadCopyLen = (srcFileLen - a) / threadNum;
			}
			System.out.println(a);
			for (int i = 0; i < threadNum; i++) {
				long start = i * threadCopyLen;
				long end = start + threadCopyLen;
				if (i == threadNum - 1) {
					end += a;
				}
				MulCopyThread t = new MulCopyThread(srcPath, destPath, start, end);
				t.setByteSize(byteSize);
				t.start();
			}

			try {
				srdaf.close();
				drdaf.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
}
